// 中间件嵌套构造器
import compose from 'koa-compose'

// 错误提示接口
interface error_fn {
    (err:any):void
}

// 末位函数接口
interface end_fn {
    (ctx:any):void
}

class middleware {

    // 中间件仓库
    public store:commonInf.mdl[]
    public constructor (store:any[] = []){
        this.store = store;
    }
    
    /* 添加中间件
    ** @params:
        [fn]: 中间件方法
    ** @return:
        middleware对象,链式调用
    */
    
    use (fn:any){
        if (typeof fn !== 'function') throw new TypeError('middleware must be a function!');

        this.store.push(fn)
        
        return this;
    }

    /* 构建流程
    ** @params:
        [params]: 上下文参数
        [end]:结束回调
        [onerror]: 错误回调
    ** @return:
        promise对象
    */
    
    action (ctx, end?:end_fn, onerror?:error_fn){
        let fnMiddleware = compose(this.store);
        let err = onerror || this.onerror;
        let res = end ?  function(){return  end(ctx)} : function (){};
        
        return fnMiddleware(ctx).then(res).catch(err);       
    }

    // 默认错误处理
    onerror(err:any){

        let err_info = JSON.stringify(err, null, 4);
        
        console.error(`
            middleware Error:
            ${err_info}
        `)
    }
}
  
export default middleware;
